package ioc

import (
	grpc2 "booksmart/book/payment/grpc"
	"booksmart/book/pkg/grpcx"
	"booksmart/book/pkg/grpcx/registry/nacos"
	"booksmart/book/pkg/logger"
	"booksmart/book/pkg/netx"
	"context"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"strconv"
)

func InitGRPCxServer(wesvc grpc2.WechatServiceServer, Client naming_client.INamingClient, l logger.LoggerV1) *grpcx.Server {
	type Config struct {
		Port    uint64  `yaml:"port"`
		Weight  float64 `yaml:"weight"`
		Enable  bool    `yaml:"enable"`
		Healthy bool    `yaml:"healthy"`
		Addr    string  `yaml:"addr"`
	}

	var cfg Config
	err := viper.UnmarshalKey("grpc.server", &cfg)
	if err != nil {
		panic(err)
	}
	grpcServer := grpc.NewServer(grpc.ChainUnaryInterceptor(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {

		return handler(ctx, req)
	}))
	wesvc.Register(grpcServer)
	ip := netx.GetOutBoundIP()
	return &grpcx.Server{
		Server: grpcServer,
		Addr:   ip + ":" + strconv.Itoa(int(cfg.Port)),
		Registry: &nacos.NacosRegistryServer{
			Client:      Client,
			Ip:          ip,
			Port:        cfg.Port,
			ServiceName: "interactives",
			Weight:      cfg.Weight,
			Enable:      cfg.Enable,
			Health:      cfg.Healthy,
		},
		Logger: l,
	}

}

//func InitGRPCServer(wesvc grpc2.WechatServiceServer,
//	ecli *clientv3.Client,
//	l logger.LoggerV1) *grpcx.Server {
//	type Config struct {
//		Port    int   `yaml:"port"`
//		EtcdTTL int64 `yaml:"etcdTTL"`
//	}
//	var cfg Config
//	err := viper.UnmarshalKey("grpc.server", &cfg)
//	if err != nil {
//		panic(err)
//	}
//	server := grpc.NewServer(grpc.ChainUnaryInterceptor(
//	//logger.NewLoggerInterceptorBuilder(l).BuildUnaryServerInterceptor(),
//	))
//	wesvc.Register(server)
//	return &grpcx.Server{
//		Server:     server,
//		Port:       cfg.Port,
//		Name:       "payment",
//		L:          l,
//		EtcdTTL:    cfg.EtcdTTL,
//		EtcdClient: ecli,
//	}
//}
